#!/bin/sh

# Let's clear out older versions of XQuartz from MacOSForge.org

[ -f /etc/paths.d/XQuartz ] && rm /etc/paths.d/XQuartz
[ -f /etc/manpaths.d/XQuartz ] && rm /etc/manpaths.d/XQuartz

[ -d /opt/X11/include/libpng12 ] && rm -rf /opt/X11/include/libpng12
[ -f /opt/X11/bin/libpng12-config ] && rm /opt/X11/bin/libpng12-config

[ -d /opt/X11/include/libpng14 ] && rm -rf /opt/X11/include/libpng14
[ -f /opt/X11/bin/libpng14-config ] && rm /opt/X11/bin/libpng14-config

[ -d /opt/X11/include/libpng15 ] && rm -rf /opt/X11/include/libpng15
[ -f /opt/X11/bin/libpng15-config ] && rm /opt/X11/bin/libpng15-config

if [ -f /Library/LaunchDaemons/org.macosforge.xquartz.privileged_startx.plist ] ; then
    /bin/launchctl unload -w /Library/LaunchDaemons/org.macosforge.xquartz.privileged_startx.plist
    rm /Library/LaunchDaemons/org.macosforge.xquartz.privileged_startx.plist
fi

if [ -f /Library/LaunchAgents/org.macosforge.xquartz.startx.plist ] ; then
    rm /Library/LaunchAgents/org.macosforge.xquartz.startx.plist
fi

OLDER_PACKAGE_ID=org.macosforge.xquartz.pkg

pkgutil --files ${OLDER_PACKAGE_ID} 2> /dev/null | grep opt/X11 | tail -r | while read file ; do
    [ -f "/${file}" -o -h "/${file}" ] && rm -f "/${file}"
    [ -d "/${file}" ] && rmdir "/${file}"
done
pkgutil --forget ${OLDER_PACKAGE_ID}

# Cleanup after buggy font caching script (cf: https://github.com/XQuartz/XQuartz/issues/127)
if [ -d /opt/X11/opt/X11/share/system_fonts ] ; then
    rm -rf /opt/X11/opt/X11/share/system_fonts
    rmdir /opt/X11/opt/X11/share
    rmdir /opt/X11/opt/X11
    rmdir /opt/X11/opt
fi

exit 0
